package it.fc.utils.singleton;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;

import org.apache.log4j.Logger;

public class ServiceLocator {

    private static DataSource dsMysql;
    private static Logger     log = Logger.getLogger(ServiceLocator.class);

    private ServiceLocator() {

    }

    private static DataSource getDatasource() {

        DataSource ds = null;
        try {
            Context initContext = new InitialContext();
            Context envContext = (Context) initContext.lookup("java:/comp/env");
            ds = (DataSource) envContext.lookup("jdbc/mySQL");
            log.info("LOOKUP SUCCESSFUL!! >> " + ds);
        } catch (NamingException e) {
            log.debug("Errore nella lookup");
            e.printStackTrace();
        }

        return ds;
    }

    public static DataSource lookup() {
        if (dsMysql == null) {
            dsMysql = ServiceLocator.getDatasource();
        }

        return dsMysql;
    }
}
